﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;

namespace CK.Sprite.Cache
{
    /// <summary>
    /// 本地缓存接口
    /// </summary>
    /// <typeparam name="T">缓存实体</typeparam>
    public interface ILocalCache<T>
    {
        List<T> GetAll(string applicationCode = default);

        Dictionary<Guid,T> GetAllDict(string applicationCode = default);
    }

    public abstract class BaseLocalCache<T> : ILocalCache<T>
    {
        protected IServiceProvider _serviceProvider => ServiceLocator.ServiceProvider;
        protected readonly object ServiceProviderLock = new object();
        protected TService LazyGetRequiredService<TService>(ref TService reference)
            => LazyGetRequiredService(typeof(TService), ref reference);

        protected TRef LazyGetRequiredService<TRef>(Type serviceType, ref TRef reference)
        {
            if (reference == null)
            {
                lock (ServiceProviderLock)
                {
                    if (reference == null)
                    {
                        reference = (TRef)_serviceProvider.GetRequiredService(serviceType);
                    }
                }
            }

            return reference;
        }

        public abstract List<T> GetAll(string applicationCode = default);

        public abstract Dictionary<Guid, T> GetAllDict(string applicationCode = default);

        public abstract string CacheKey { get; }
    }
}
